package com.mxx.bu_yang.activity;

import android.content.Intent;
import android.util.Patterns;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.mxx.basic.server.RetrofitHelper;
import com.mxx.basic.server.enums.RequestEnum;
import com.mxx.basic.utils.SPUtils;
import com.mxx.basic.utils.ToastUtils;
import com.mxx.bu_yang.R;
import com.mxx.bu_yang.common.CommonTitleActivity;
import com.mxx.common.config.ConstantsConfig;
import com.mxx.common.config.NetUrlConfig;
import com.mxx.common.observer.DefaultModelObserver;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends CommonTitleActivity {
    private EditText edt_account;
    private EditText edt_password;
    private LinearLayout ll_ip;
    private EditText edt_ip;
    private LinearLayout ll_ip1;
    private EditText edt_ip1;
    private LinearLayout ll_id;
    private EditText edt_id;
    private TextView tv_login;
    private TextView tv_setting;
    private int clickCount;

    @Override
    protected int getTitleType() {
        return TITLE_ONLY_LEFT_BACK;
    }

    /**
     * 获取当前页面的布局文件
     *
     * @return int
     */
    @Override
    public int getLayoutResId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        super.initView();
        String s = (String) SPUtils.get(this, "login_info", "");
        if (s != null && !s.isEmpty()) {
            skipToMain();
            return;
        }
        edt_account = findViewById(R.id.edt_account);
        edt_password = findViewById(R.id.edt_password);
        ll_ip = findViewById(R.id.ll_ip);
        edt_ip = findViewById(R.id.edt_ip);
        ll_ip1 = findViewById(R.id.ll_ip1);
        edt_ip1 = findViewById(R.id.edt_ip1);
        ll_id = findViewById(R.id.ll_id);
        edt_id = findViewById(R.id.edt_id);
        tv_login = findViewById(R.id.tv_login);
        tv_setting = findViewById(R.id.tv_setting);

        String ip = (String) SPUtils.get(this, ConstantsConfig.BASE_URL, "");
        if (ip == null || ip.isEmpty()) {
            ip = NetUrlConfig.BASE_URL;
        }
        edt_ip.setText(ip);
        String ip1 = (String) SPUtils.get(this, ConstantsConfig.UPGRADE_URL, "");
        edt_ip1.setText(ip1);
        String id = (String) SPUtils.get(this, ConstantsConfig.APPLY_ID, "");
        edt_id.setText(id);
    }

    @Override
    protected void doSomething(boolean isPopup, int keyboardHeight) {
        super.doSomething(isPopup, keyboardHeight);
    }

    @Override
    public void initListener() {
        super.initListener();
        if (tv_login != null) {
            tv_login.setOnClickListener(this);
        }
        if (tv_setting != null) {
            tv_setting.setOnClickListener(this);
        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.tv_login) {
            checkLogin();
        }
        if (view.getId() == R.id.tv_setting) {
            clickCount++;
            if ((clickCount % 2) == 0) {
                ll_id.setVisibility(View.VISIBLE);
                ll_ip.setVisibility(View.VISIBLE);
                ll_ip1.setVisibility(View.VISIBLE);
            } else {
                ll_id.setVisibility(View.GONE);
                ll_ip.setVisibility(View.GONE);
                ll_ip1.setVisibility(View.GONE);
            }
        }
    }

    private void checkLogin() {
        String account = edt_account.getText().toString();
        String password = edt_password.getText().toString();
        String ip = edt_ip.getText().toString();
        String ip1 = edt_ip1.getText().toString();
        String id = edt_id.getText().toString();
        if (account == null || account.isEmpty()) {
            ToastUtils.showToast(this, "请输入账号/手机号");
            return;
        }
        if (password == null || password.isEmpty()) {
            ToastUtils.showToast(this, "请输入登录密码");
            return;
        }
        if (ip == null || ip.isEmpty()) {
            ToastUtils.showToast(this, "请输入IP，并以/结尾");
            ll_ip.setVisibility(View.VISIBLE);
            return;
        }

        boolean isValid = isValid(ip);
        if (!isValid) {
            ToastUtils.showToast(this, "IP地址不合法");
            return;
        }
        if (ip1 == null || ip1.isEmpty()) {
            ToastUtils.showToast(this, "请输入IP，并以/结尾");
            ll_ip1.setVisibility(View.VISIBLE);
            return;
        }

        boolean isValid1 = isValid(ip1);
        if (!isValid1) {
            ToastUtils.showToast(this, "IP地址不合法");
            return;
        }
        if (id == null || id.isEmpty()) {
            ToastUtils.showToast(this, "请输入应用唯一标识");
            ll_id.setVisibility(View.VISIBLE);
            return;
        }
        saveIp(ip);
        saveIp1(ip1);
        saveId(id);
//        skipToMain();
        login(account, password);
    }

    private void saveIp(String ip) {
        SPUtils.put(this, ConstantsConfig.BASE_URL, ip);
    }

    private void saveIp1(String ip1) {
        SPUtils.put(this, ConstantsConfig.UPGRADE_URL, ip1);
    }

    private void saveId(String id) {
        SPUtils.put(this, ConstantsConfig.APPLY_ID, id);
    }

    private boolean isValid(String urlString) {
        return URLUtil.isValidUrl(urlString) && Patterns.WEB_URL.matcher(urlString).matches();
    }

    private void login(String account, String password) {
        Map<String, String> params = new HashMap<>();
        params.put("userName", account);
        params.put("password", password);
        String json = new Gson().toJson(params);
        String baseUrl = (String) SPUtils.get(this, ConstantsConfig.BASE_URL, "");
        if (baseUrl == null || baseUrl.isEmpty()) {
            runOnUiThread(() -> ToastUtils.showToast(LoginActivity.this, "请重新设置IP"));
            return;
        }


        try {
            new RetrofitHelper
                    .Builder()
                    .baseUrl(baseUrl)
                    .appendUrl("user/operationScanUser/login")
                    .addParams(json)
                    .build()
                    .observable(RequestEnum.METHOD_POST_JSON_STRING)
                    .subscribe(new DefaultModelObserver(this) {
                        @Override
                        protected void handlerJsonObjectData(String objectJson) {
                            mLogger.i("");
                            saveLoginInfo(objectJson);
                            skipToMain();
                        }

                        @Override
                        protected void onFailed(int code, String msg) {
                            super.onFailed(code, msg);
                            ToastUtils.showToast(LoginActivity.this, code+"\n"+msg);
                        }
                    });
        } catch (Exception e) {
            ToastUtils.showToast(this,e.getMessage());
        }
    }

    private void saveLoginInfo(String response) {
        if (response == null || response.isEmpty()) {
            return;
        }
        SPUtils.put(this, "login_info", response);
    }

    private void skipToMain() {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }
}